package main

import (
	"context"
	"flag"
	"github.com/golang/glog"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	flag.Parse()
	defer glog.Flush()
	glog.V(2).Info("Starting http server...")
	srv := http.Server{
		Addr:    ":5000",
		Handler: http.HandlerFunc(ServeHTTP),
	}
	//优雅终止
	done := make(chan os.Signal, 1)
	//这里不能捕捉SIGINT,防止杀不死
	signal.Notify(done, os.Interrupt, syscall.SIGTERM)

	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()
	log.Print("Server Started")
	<-done
	log.Print("Server Stopped")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer func() {
		cancel()
	}()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatalf("Server Shutdown Failed:%+v", err)
	}
	log.Print("Server Exited Properly")
}
